package nl.hva.web.mvcwebapp.controllers;

import java.io.*;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import javax.servlet.*;
import javax.servlet.http.*;
import nl.hva.web.mvcwebapp.models.Course;
import nl.hva.web.mvcwebapp.service.HibernateUtil;
import org.hibernate.Hibernate;
import org.hibernate.Session;
import org.hibernate.Transaction;
import java.util.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.HashSet;
import java.util.Set;
import nl.hva.web.mvcwebapp.doa.ChapterDAO;
import nl.hva.web.mvcwebapp.doa.CourseDAO;
import nl.hva.web.mvcwebapp.doa.UserDAO;
import nl.hva.web.mvcwebapp.models.Chapter;
import nl.hva.web.mvcwebapp.models.CourseUser;
import nl.hva.web.mvcwebapp.models.News;
import nl.hva.web.mvcwebapp.models.User;

public class CourseController extends HttpServlet {

    private String address = "/course.jsp";
    ArrayList paths_jsp = new ArrayList();
    ArrayList paths = new ArrayList();
    public static HttpSession session_user;

    /*
     * HTTP GET request
     */
    public ArrayList getPaths() {
        ArrayList paths = new ArrayList();
        paths.add(0, "/course/catalog");
        paths.add(1, "/course/view");
        paths.add(2, "/course/edit");
        paths.add(3, "/course/new");
        paths.add(4, "/course/delete");
        paths.add(5, "/course/enroll");
        paths.add(6, "/course/livestream");
        paths.add(7, "/course/mycourses");
        return paths;
    }

    public ArrayList getPathsJSP() {
        ArrayList paths_jsp = new ArrayList();
        paths_jsp.add(0, "/course/course_catalog.jsp");
        paths_jsp.add(1, "/course/course_view.jsp");
        paths_jsp.add(2, "/course/course_edit.jsp");
        paths_jsp.add(3, "/course/course_edit.jsp");
        paths_jsp.add(4, "/course/course_catalog.jsp");
        paths_jsp.add(5, "/course/course_catalog.jsp");
        paths_jsp.add(6, "/course/course_livestream.jsp");
        paths_jsp.add(7, "/course/my_courses.jsp");


        return paths_jsp;
    }

    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws IOException, ServletException {

        HttpSession httpsession = request.getSession(true);

        Session session = HibernateUtil.getSessionFactory().getCurrentSession();
        Transaction tx = session.beginTransaction();
        boolean redirect = false;
        ArrayList paths = getPaths();
        ArrayList paths_jsp = getPathsJSP();
        String path = request.getServletPath();
        for (int i = 0; i < paths.size(); i++) {
            try {
                if (path.equals(paths.get(i).toString())
                        || path.substring(0, path.toString().length() - 1).equals(paths.get(i).toString())) {
                    System.out.println(i);
                    // /course/catalog
                    System.out.println(i);
                    if (i == 0) {
                        
                        List<Course> courselist = CourseDAO.getAllCourses();
                        request.setAttribute("courses", courselist);
                        request.setAttribute("amountcourses", courselist.size());
                    } // /course/view
                    else if (i == 1) {
                        int id = Integer.parseInt(request.getParameter("id"));
                        Course course = CourseDAO.getCourse(id);
                        List<CourseUser> userlist = CourseDAO.getAllUsersFromCourse(course);
                        //int userid = Integer.parseInt((String)httpsession.getAttribute("user_id"));
                        HttpSession session_user = request.getSession(true);
                        String firstname = (String) session_user.getAttribute("user_firstname");
                        int user_id = 0;
                        if (firstname != null) {
                            user_id = Integer.valueOf("" + session_user.getAttribute("user_id"));
                        }
                        request.setAttribute("users", userlist);
                        request.setAttribute("amountusers", userlist.size());
                        //int userid = UserController.userAccountId;
                        if (firstname != null) {
                            User user = UserDAO.getUser(user_id);
                            if (CourseDAO.isEnrolled(course, user)) {
                                System.out.println("is enrolled");
                                request.setAttribute("enrolled", true);
                            } else {
                                System.out.println("is  NOT enrolled");
                                request.setAttribute("enrolled", false);
                            }
                        }else{
                            request.setAttribute("enrolled", false);
                        }

                        List<Chapter> chapterlist = ChapterDAO.getAllChapters(course.getCourseid());
                        request.setAttribute("course", course);
                        request.setAttribute("chapters", chapterlist);
                        request.setAttribute("Headteacher", course.getHeadteacher());
                        request.setAttribute("progress", 75);
                    }// /course/edit
                    else if (i == 2) {
                        int id = Integer.parseInt(request.getParameter("id"));
                        Course course = CourseDAO.getCourse(id);
                        request.setAttribute("course", course);
                        request.setAttribute("pageTitle", "Edit Course");
                        request.setAttribute("buttonTitle", "Edit");
                        List<User> teacherlist = UserDAO.getAllTeachers();
                        // loopje om alles wat geen teacher is uit de lijst users te extracten.
                        for (int extraction = 0; extraction < teacherlist.size(); extraction++) {
                            if (teacherlist.get(extraction).getUserType() != 2) {
                                teacherlist.remove(extraction);
                            }
                        }
                        request.setAttribute("teachers", teacherlist);
                        request.setAttribute("amountteachers", teacherlist.size());
                    }// /course/new
                    else if (i == 3) {
                        request.setAttribute("pageTitle", "New Course");
                        request.setAttribute("buttonTitle", "Add");;
                        List<User> teacherlist = UserDAO.getAllTeachers();
                        // loopje om alles wat geen teacher is uit de lijst users te extracten.
                        for (int extraction = 0; extraction < teacherlist.size(); extraction++) {
                            if (teacherlist.get(extraction).getUserType() != 2) {
                                teacherlist.remove(extraction);
                            }
                        }
                        request.setAttribute("teachers", teacherlist);
                        request.setAttribute("amountteachers", teacherlist.size());
                    }// /course/delete
                    else if (i == 4) {
                        int id = Integer.parseInt(request.getParameter("courseid"));
                        CourseDAO.deleteCourse(id);
                        redirect = true;
                        response.sendRedirect(response.encodeRedirectURL("../course/catalog"));
                    } else if (i == 5) {
                        int courseid = Integer.parseInt(request.getParameter("courseid"));
                        //int userid = 2;
                        HttpSession session_user = request.getSession(true);
                        String firstname = (String) session_user.getAttribute("user_firstname");
                        int user_id = 0;
                        if (firstname != null) {
                            user_id = Integer.valueOf("" + session_user.getAttribute("user_id"));
                        }
                        Course course = new Course();
                        User user = new User();
                        course = CourseDAO.getCourse(courseid);
                        user = UserDAO.getUser(user_id);
                        CourseDAO.enrollUser(course, user);


                        redirect = true;
                        response.sendRedirect(response.encodeRedirectURL("../course/view?id=" + courseid + ""));
                    } else if (i == 7) {
                        session_user = request.getSession();
                        int user_id = Integer.valueOf("" + session_user.getAttribute("user_id"));
                        System.out.println(user_id);
                        User user = UserDAO.getUser(user_id);
                        List<CourseUser> courselist = CourseDAO.getAllCoursesFromUser(user);
                        request.setAttribute("courses", courselist);
                        request.setAttribute("amountcourses", courselist.size());
                    }
                    address = paths_jsp.get(i).toString();
                }
            } catch (Exception E) {
            }
        }

        request.setAttribute("path", path);
        if (!redirect) {
            RequestDispatcher dispatcher = request.getRequestDispatcher(address);
            dispatcher.forward(request, response);
        }

    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws IOException, ServletException {
        ArrayList paths = getPaths();
        ArrayList paths_jsp = getPathsJSP();
        Session session = HibernateUtil.getSessionFactory().getCurrentSession();
        Transaction tx = session.beginTransaction();
        String path = request.getServletPath();
        for (int i = 0; i < paths.size(); i++) {
            try {
                if (path.equals(paths.get(i).toString())
                        || path.substring(0, path.toString().length() - 1).equals(paths.get(i).toString())) {
                    address = paths_jsp.get(i).toString();
                    // ---------------- /course/update --------------------
                    if (i == 2) {
                        System.out.println("update");
                        int userid = 2;
                        User user = UserDAO.getUser(userid);
                        CourseDAO.updateCourse(request, user);
                        response.sendRedirect(response.encodeRedirectURL("../course/catalog"));
                    }// ---------------- /course/new --------------------
                    else if (i == 3) {
                        System.out.println("new");
                        int userid = 2;
                        User user = UserDAO.getUser(userid);
                        CourseDAO.insertCourse(request, user);
                        response.sendRedirect(response.encodeRedirectURL("../course/catalog"));
                    }
                }

            } catch (Exception E) {
            }
        }

    }
}
